package ms.server.api.exception;

import ms.server.api.bean.vo.ResultCode;
import ms.server.api.bean.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理器
 *
 * @Author ybc
 * @Date 2021/6/25 11:43
 */
@ResponseBody
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 业务异常
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    public ResultVO businessHandler(HttpServletRequest request, BusinessException exception){
        log.error("business Exception : {}",exception.getMessage());
        return new ResultVO(exception.getCode(), exception.getMessage(),null);
    }

    /**
     * 处理空指针的异常
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultVO exceptionHandler(HttpServletRequest request, NullPointerException exception){
        log.error("NullPointer Exception : {}",exception.getMessage());
        return new ResultVO(ResultCode.UNKNOWN_EXCEPTION,null);
    }

    /**
     * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultVO exceptionHandler(HttpServletRequest req, Exception e){
        log.error("unknow Exception : {}",e.getMessage());
        return new ResultVO(ResultCode.SERVER_ERROR,null);
    }

}
